const express = require('express');

const router = express.Router();

const Dept = require('../models/Dept.js');
const Emp = require('../models/Emp.js');

// GET `/emp/list`
router.get( '/emp/list' , (req,resp) => {
    Emp.findAll({
        attributes: [ 'id' , 'name']
    }).then( rows => rows.map( row => row.dataValues ) )
    .then( emps => {
        resp.render( 'emp/list' , { emps: emps });
    }).catch( reason => {
        resp.render( 'emp/list' , { reason: reason });
    })
});

// GET `/emp/add`
router.get( '/emp/add' , (req,resp) => {
    Dept.findAll({
        attributes: [ 'id' , 'name' ]
    }).then( rows => { 
        let arr = rows.map( row => row.dataValues ) 
        return arr ;
    }).then( depts => {
        resp.render( 'emp/add' , { depts } );
    }).catch( reason => {
        resp.render( 'emp/add' , { reason } );
    })
});

// POST `/emp/add`
router.post( '/emp/add' , (req,resp) => {
    let { empName , deptId } = req.body ;
    Emp.create( { 
        name: empName , 
        deptId 
    }).then( emp => {
        console.log( '由数据库产生的主键: ' , emp.dataValues.id );
        resp.redirect( '/emp/list' );
    }).catch( reason => {
        resp.redirect( '/emp/add' );
    })
});

module.exports = router;